<?php
//session_start();
include_once $_SERVER['DOCUMENT_ROOT']."/math-videos/configure.inc.php";
//check if you have curl loaded
//echo $_REQUEST['json'];
$title ='';
$abstract ='';
$lectureDate ='';
$duration ='';
$type ='';
$remoteURL= '';
$location= '';
$eventTitle= '';
$mscNumbers= '';
$keywords= '';
$familyName= '';
$givenName= '';
$middleName= '';
$suffix= ''; 
$altName= ''; 
$title= ''; 
$department= ''; 
$company= ''; 
$timecode= ''; 
$timecode_type= ''; 
$data= ''; 

$rating=0;
$views=0;
$thumbnail ='';

$timecode_sha1='';
$asset_title ='';


$data_string = json_decode($_REQUEST['json'],true);
foreach($data_string as $key=>$value)
{
	if($key=='presenters')
	{
		if(is_array($value))
		{ 
			unset($presenters_array);
			if(isset($value[0]))
			{
				
				for($i=0;$i<count($value);$i++)
				{
					foreach($value as $key1=>$value1)
					{
						 $$key1 = trim($value1);
					//	 echo "$key1 = $value1<br>";
						 $presenters_array[$i][$key1]=$value1;
					}
				}
			}
			else
			{
				 foreach($value as $key1=>$value1)
					{
						 $$key1 = trim($value1);
					//	 echo "$key1 = $value1<br>";
						 $presenters_array[0][$key1]=$value1;
					}
			}
		}
	}	
	elseif($key=='timecode')
	{
		if(is_array($value))
		{ 
		  unset($timecode_array);
			if(isset($value[0]))
			{
				for($i=0;$i<count($value);$i++)
				{
					foreach($value[$i] as $key2=>$value2)
					{
						 $$key2 = trim($value2);
					//	 echo "$key2 = $value2<br>";
						 $timecode_array[$i][$key2]=$value2;
					}					
				}
			}
			else
			{
				 foreach($value as $key2=>$value2)
					{
						 $$key2 = trim($value2);
					//	 echo "$key2 = $value2<br>";
						 $timecode_array[0][$key2]=$value2;
					}	
			}
		}
	}
	elseif($key=='keywords')
	{
		if(is_array($value))
		{ 
		  unset($keyword_array);
			 sort($value);
			for($t=0;$t<count($value); $t++)
			{
				$keyword_array[]=$value[$t];
			}
		}
	}
	elseif($key=='mscNumbers')
	{
		if(is_array($value))
		{ 
		  unset($msc_array);
		  sort($value);
			for($t=0;$t<count($value); $t++)
			{
				$msc_array[]=$value[$t];
			}
		}
	}
	elseif($key=='thumbnail')
	{
		if(is_array($value))
		{ 
		  unset($thumbnail_array);
		  foreach($value as $key2=>$value2)
			{
				$$key2 = trim($value2);
				//$thumbnail_array[$key2]=$value2;
				//	$thumbnail_array[$key2]= unserialize(gzuncompress(stripslashes(base64_decode(strtr($value2, '-_,', '+/=')))));
				if($key2 == 'image')
				{
					//$thumbnail_array[$key2]=urldecode($value2);
					//$thumbnail_array[$key2]=$value2;
					$thumbnail_array[$key2]= unserialize(gzuncompress(stripslashes(base64_decode(strtr($value2, '-_,', '+/=')))));
				}
				else
				{
					$thumbnail_array[$key2]=$value2;
				}
			}	
		}
	}
	else
	{
		$$key = trim($value);
//	 echo "$key = $value<br>";
		if($key=='title')
		{
			$asset_title = $title;
		}
	}
}  
//authertication user
$sqltext="select id as user_id , institute_id from users  WHERE username=? and password=?";
$params = array();

array_push($params,sql_escape($username));
array_push($params,sql_escape($password));
$result = db_select_query($conn2,$sqltext,$params);
$user_id='';
$institute_id='';
while($row = db_fetch_array($result))
{
	$user_id = $row['user_id'];
	$institute_id = $row['institute_id'];
}

if($user_id =='')
{
//	echo "HTTP/1.1 401 <br />";
	header('HTTP/1.1 401 Authorization Required');
//	echo "Date: ".gmdate('F j, Y, g:i:s')." GMT<br />";
//	echo "Location: https://api.mathinstitutes.org/metadata/v1/asset/2341<br />";
	echo "{\"error\": \"Authorization Required.\"}";
}
else
{
//“error”: “missing required field - title”//
    //update asset table 
	$id= $assetID;
	$update_flag= false;			
	//check if user has right to upf=date this asset
	$sqltext="select title from asset WHERE id=? and institute_id = ?";
	$params = array();

	array_push($params,sql_escape($id));
	array_push($params,sql_escape($institute_id));
	$result = db_select_query($conn,$sqltext,$params);
	while($row = db_fetch_object($result))
	{
		foreach ($row as $key => $value) 
		{
			$update_flag= true;			
		}
	}
	if($update_flag)
	{
		//end get info
		//check required fields
	
		//“error”: “missing required field - title”//
		$error_message ='';
		if(!isset($asset_title) ||  $asset_title=='')
		{
			$error_message .= "{\"error\": \"missing required field - title\"}";
		}
		if(!isset($lectureDate) ||  $lectureDate=='')
		{
		 $error_message .= "{\"error\": \"missing required field - lectureDate\"}";
		}
		if(!isset($remoteURL) ||  $remoteURL=='')
		{
		 $error_message .= "{\"error\": \"missing required field - remoteURL\"}";
		}
		if(!isset($location)||  $location=='' )
		{
		 $error_message .= "{\"error\": \"missing required field - location\"}";
		}
		if(!isset($presenters_array))
		{
		 $error_message .= "{\"error\": \"missing required field - presenter\"}";
		}
		if($error_message  =='')
		{
			//$first_name = $presenter_first_name;
			//$last_name = $presenter_last_name;
			//build checksum
			$presenter_checksum='';
			if(isset($presenters_array))
			{
				unset($presenters_list);
				for($i=0;$i<count($presenters_array); $i++)
				{
					foreach($presenters_array[$i] as $key=>$value)
					{
						 $$key = trim($value);
					}				
					$presenters_list[] = $familyName.$givenName.$middleName.$suffix.$altName.$title.$department.$company;		
				}
				if(isset($presenters_list) )
				{
					sort($presenters_list);
					for($i=0;$i<count($presenters_list); $i++)
					{
						$presenter_checksum .= $presenters_list[$i];
						
					}
				}
			}
			
			$timecode_checksum='';
			if(isset($timecode_array))
			{
				unset($timecode_list);
				for($i=0;$i<count($timecode_array); $i++)
				{
					foreach($timecode_array[$i] as $key=>$value)
					{
						 $$key = trim($value);
					}				
					$timecode_list[] = $timecode.$time_code_type.$data;		
				}
				if(isset($timecode_list) )
				{
					sort($timecode_list);
					for($i=0;$i<count($timecode_list); $i++)
					{
						$timecode_checksum .= $timecode_list[$i];
					}
				}
				$timecode_sha1 = sha1($timecode_checksum);
			}
			$msc_list ='';
			if(isset($msc_array))
			{
				for($i=0;$i<count($msc_array); $i++)
				{
					$msc_list .= $msc_array[$i];
				}
				
			}
			$keywords_list ='';
			if(isset($keyword_array))
			{
				for($i=0;$i<count($keyword_array); $i++)
				{
					$keywords_list .= $keyword_array[$i];
				}
				
			}
		
			$asset_string =$asset_title.$abstract.$lectureDate.$duration.$type.$remoteURL.$location.$eventTitle.$msc_list.$keywords_list.$presenter_checksum;
		//	echo $asset_string."<br>";
			$asset_sha1 = sha1($asset_string);
		//	echo $asset_sha1."<br>";
			$statistics_sha1 ='';
			if($rating!='' || $views!='')
			{
				$statistics_sha1 = sha1($rating.$views);
			}
			$thumbnail_sha1 ='';
			if(isset($thumbnail_array) && $thumbnail_array !='' )
			{			
				$thumbnail_sha1 = sha1($thumbnail_array['image'].$thumbnail_array['type']);
			}
			$params = array();
			$sqltext="UPDATE asset SET ";
			//if(isset($asset_title) && $asset_title !='')
		//	{
				$sqltext .="title =?,";
				array_push($params,sql_escape($asset_title));
		//	}
		//	if(isset($abstract) && $abstract !='')
			//{
				$sqltext .="abstract =?,";
				array_push($params,sql_escape($abstract));
			//}
		//	if(isset($lectureDate) && $lectureDate !='')
		//	{
				$sqltext .="lecture_date =?,";
				array_push($params,date("Y-m-d H:i:s",$lectureDate));
			//}
				if(isset($duration) && $duration !='')
				{
					$sqltext .="duration =?,";
					array_push($params,sql_escape($duration));
				}
				else
				{
					 $sqltext .="duration =?,";
					 array_push($params,0);
				}
		//	if(isset($asset_type) && $asset_type !='')
			//{
				$sqltext .="asset_type =?,";
				array_push($params,sql_escape($asset_type));
		//	}
	
		//	if(isset($remote_url) && $remote_url !='')
		//	{
				$sqltext .="remote_url =?,";
				array_push($params,sql_escape($remoteURL));
			//}
			//if(isset($location) && $location !='')
		//	{
				$sqltext .="location =?,";
				array_push($params,sql_escape($location));
		//	}
	
			//if(isset($event_title) && $event_title !='')
		//	{
				$sqltext .="event_title =?,";
				array_push($params,sql_escape($eventTitle));
			//}
			$sqltext .="last_modified_datetime =?,";
			array_push($params,date("Y-m-d H:i:s"));
			$sqltext .="last_modified_by =?";
			array_push($params,sql_escape($user_id));
			if(isset($rating) && $rating !='')
			{
				$sqltext .=",rating =?";
				array_push($params,sql_escape($rating));
			}
			else
			{
				 $sqltext .=",rating =?";
				array_push($params,0);
			}
			if(isset($views) && $views !='')
			{
				$sqltext .=",views =?";
				array_push($params,sql_escape($views));
			}
			else
			{
				 $sqltext .=",views =?";
				array_push($params,0);
			}
			//if(isset($thumbnail) && $thumbnail !='')
			//{
			//	$sqltext .=",thumbnail =?";
			//	array_push($params,sql_escape($thumbnail));
			//}
			$sqltext .=",assetSHA1 =?";
			array_push($params,sql_escape($asset_sha1));
			
			$sqltext .=",timecodeSHA1 =?";
			array_push($params,sql_escape($timecode_sha1));
		
			$sqltext .=",statisticsSHA1 =?";
			array_push($params,sql_escape($statistics_sha1));
			$sqltext .=",thumbnailSHA1 =?";
			array_push($params,sql_escape($thumbnail_sha1));
			if(isset($thumbnail_array) && $thumbnail_array !='' )
			{		
				$sqltext .=",thumbnail_type =?";
				array_push($params,sql_escape($thumbnail_array['type']));
				$image_name =$id."_thumb.".$thumbnail_array['type'];
			//$image_name =$id."_thumb".$thumbnail_array['type'];
				/*$thumbnail_image_file = $institute_id."/".$id."/".$image_name;	
				$sqltext .=",thumbnail =?";
				array_push($params,sql_escape($thumbnail_image_file));*/
		
			}
			else
			{
				$sqltext .=",thumbnail_type =?";
				array_push($params,sql_escape(''));
				/*$sqltext .=",thumbnail =?";
				array_push($params,sql_escape(''));*/
			}
			$sqltext .=" WHERE id=?";
			array_push($params,sql_escape($id));
			db_change_query($conn,$sqltext,$params);
		 // echo $id;
		 
		 //update thumbnail
		 	if(isset($thumbnail_array) && $thumbnail_array !='' )
			{	
				if(!is_dir($_SERVER['DOCUMENT_ROOT']."/math-videos/images/$institute_id"))
				{
					mkdir($_SERVER['DOCUMENT_ROOT']."/math-videos/images/$institute_id", 0777); 
					mkdir($_SERVER['DOCUMENT_ROOT']."/math-videos/images/$institute_id/$id", 0777); 
				}
				elseif(!is_dir($_SERVER['DOCUMENT_ROOT']."/math-videos/images/$institute_id/$id"))
				{
					mkdir($_SERVER['DOCUMENT_ROOT']."/math-videos/images/$institute_id/$id", 0777); 
				}
				$image_name =$id."_thumb.".$thumbnail_array['type'];
				//echo "image_name=$image_name<br>"; 
				$thumbnail_image_file = $institute_id."/".$id."/".$image_name;	
				$savefile = fopen($_SERVER['DOCUMENT_ROOT']."/math-videos/images/$thumbnail_image_file", 'wb');
				fwrite($savefile, $thumbnail_array['image']);
				fclose($savefile);
				//	$content=	file_get_contents($site_http."images/".$thumbnail_image_file);
				//echo '<img src="data:image/".$thumbnail_array['image'].";base64,' .$content. '" />';
			}
			//update presenter
			//delete and insert again( all data need be posted)
			$sqltext="DELETE From presenter where asset_id=? ";
			$params = array();
			array_push($params,sql_escape($id));
			db_change_query($conn,$sqltext,$params);
			
			if(isset($presenters_array)  && $presenters_array !='')
			{					
				for($i=0;$i<count($presenters_array); $i++)
				{
					$familyName= '';
					$givenName= '';
					$middleName= '';
					$suffix= ''; 
					$altName= ''; 
					$title= ''; 
					$department= ''; 
					$company= ''; 	
					foreach($presenters_array[$i] as $key=>$value)
					{
						 $$key = trim($value);
					}				
					
					$sqltext="INSERT INTO presenter(asset_id, first_name, last_name, middle_name, alt_name, suffix, title, department, organization) values( ?, ?, ?, ?, ? ,?,?,?,?)";
					$params = array();
					array_push($params,sql_escape($id));
					array_push($params,sql_escape($givenName));
					array_push($params,sql_escape($familyName));
					array_push($params,sql_escape($middleName));
					array_push($params,sql_escape($altName));
					array_push($params,sql_escape($suffix));
					array_push($params,sql_escape($title));// job title
					array_push($params,sql_escape($department));
					array_push($params,sql_escape($company));
					db_change_query($conn,$sqltext,$params);
				}
						
			}
			/*$flag_presenter = false;
			$params = array();
			$sqltext ='';
			if(isset($presenter_first_name) && $presenter_first_name !='')
			{
				$first_name = $presenter_first_name;
				$flag_presenter = true;
				$sqltext .="first_name =?,";
				array_push($params,sql_escape($first_name));
			}
			if(isset($presenter_last_name) && $presenter_last_name !='')
			{
				$last_name = $presenter_last_name;
				$flag_presenter = true;
				$sqltext .="last_name =?,";
				array_push($params,sql_escape($last_name));
			}
			
			if(isset($department) && $department !='')
			{
				$flag_presenter = true;
				$sqltext .="department =?,";
				array_push($params,sql_escape($department));
			}
			if(isset($company) && $company !='')
			{
				$flag_presenter = true;
				$sqltext .="organization =?,";
				array_push($params,sql_escape($company));
			}
			
			if($flag_presenter)
			{
				$sqltext1="UPDATE presenter  SET ";
				$sqltext1 .= substr($sqltext,0,strlen($sqltext)-1);
				$sqltext1 .= " WHERE asset_id= ?";		
				array_push($params,sql_escape($id));
				db_change_query($conn,$sqltext1,$params);
			}*/
				//update keywords
			$sqltext="DELETE From keyword where asset_id=? ";
			$params = array();
			array_push($params,sql_escape($id));
			db_change_query($conn,$sqltext,$params);
			if(isset($keyword_array) && $keyword_array !='')
			{
				
				/*$sqltext="UPDATE keyword SET keyword=? WHERE asset_id= ?";
				$params = array();
				array_push($params,sql_escape($keyword));
				array_push($params,sql_escape($id));
				db_change_query($conn,$sqltext,$params);*/
				for($k_num=0; $k_num<count($keyword_array); $k_num++)
				{
					$sqltext="INSERT INTO keyword(asset_id, keyword) values( ?, ?)";
					$params = array();
					array_push($params,sql_escape($id));
					array_push($params,sql_escape($keyword_array[$k_num]));
					db_change_query($conn,$sqltext,$params);
				}
			}
				//update timecode
				//delete and insert again
			$sqltext="DELETE From timecode where asset_id=? ";
			$params = array();
			array_push($params,sql_escape($id));
			db_change_query($conn,$sqltext,$params);
			if(isset($timecode_array) && $timecode_array !='')
			{
				
				for($i=0;$i<count($timecode_array); $i++)
				{
					$timecode= ''; 
					$timecode_type= ''; 
					$data= ''; 
					foreach($timecode_array[$i] as $key=>$value)
					{
						 $$key = trim($value);
					}	
					$sqltext="INSERT INTO timecode(asset_id, timecode, timecode_type, data) values( ?, ?,?,?)";
					$params = array();
					array_push($params,sql_escape($id));
					array_push($params,sql_escape($timecode));
					array_push($params,sql_escape($timecode_type));
					array_push($params,sql_escape($data));
					db_change_query($conn,$sqltext,$params);
				}
			}
		/*	$flag_timecode = false;
			$params = array();
			$sqltext ='';
			if($timecode !='')
			{
				$flag_timecode = true;
				$sqltext .="timecode =?,";
				array_push($params,sql_escape($timecode));
			}
			if($timecode_type !='')
			{
				$flag_timecode = true;
				$sqltext .="timecode_type =?,";
				array_push($params,sql_escape($timecode_type));
			}
			if($data !='')
			{
				$flag_timecode = true;
				$sqltext .="data =?,";
				array_push($params,sql_escape($data));
			}
			if($flag_timecode)
			{
				$sqltext1="UPDATE timecode  SET ";
				$sqltext1 .= substr($sqltext,0,strlen($sqltext)-1);
				$sqltext1 .= "WHERE asset_id= ?";	
				array_push($params,sql_escape($id));
				db_change_query($conn,$sqltext1,$params);
			}*/
			//update msc_number
			$sqltext="DELETE From msc_number where asset_id=? ";
			$params = array();
			array_push($params,sql_escape($id));
			db_change_query($conn,$sqltext,$params);
			if(isset($msc_array) &&  $msc_array!='')
			{
				
				for($m_num=0; $m_num<count($msc_array); $m_num++)
				{
					$sqltext="INSERT INTO msc_number(asset_id, msc) values( ?, ?)";
					$params = array();
					array_push($params,sql_escape($id));
					array_push($params,sql_escape($msc_array[$m_num]));
					db_change_query($conn,$sqltext,$params);
				}
			}
			/*if($msc !='')
			{
				$sqltext="UPDATE msc_number SET  msc=? WHERE asset_id= ?";
				$params = array();
				array_push($params,sql_escape($msc));
				array_push($params,sql_escape($id));
				db_change_query($conn,$sqltext,$params);
			}*/
			//add to api log
			$sqltext="INSERT INTO api_logs(query,added_date,user_id, institute_id,asset_id) values( ?, ?, ?,?,?)";
			$params = array();
			array_push($params,'Update asset');
			array_push($params,date("Y-m-d H:i:s"));
			array_push($params,sql_escape($user_id));
			array_push($params,sql_escape($institute_id));
			array_push($params,sql_escape($id));
			db_change_query($conn,$sqltext,$params);
			
			unset($result_array);
			$result_array['assetID']=$id;		
			$result_array['assetURL']=$site_http."metadata/v1/asset/".$id;		
			$result_array['assetSHA1']=$asset_sha1;	
			header('HTTP/1.1 200 OK. Successful update of the asset.');
			//echo json_encode($result_array);
			$result=json_encode($result_array);
			if(isset($_REQUEST['callback']))
			{  
			  echo $_REQUEST['callback']. '(' . $result . ');';
			  return;
			}
			echo $result;
		//	echo "HTTP/1.1 200 OK <br />";
		//	echo "Date: ".gmdate('D, j F Y g:i:s')." GMT<br />";
					//echo "Content-Type: application/json<br />";
		//	echo "Location: ".$site_http."metadata/v1/asset/$id<br />";
		/*	echo "{ <br />\"assetID\": $id, <br />
									\"assetURL\": ".$site_http."metadata/v1/asset/$id\" <br />
									\"assetSHA1\": \"".$asset_sha1."\"<br />
									}";*/
			//return json array
			/*$result_array = array("title" => "$title", 
						"lecture_date"=> "$lecture_date",
						"remote_url" => "$remote_url",
						"organization" => "$organization",
						"presenter" => "$first_name $last_name",
						"job_title" => "$job_title",
						"keyword" => "$keyword",
						"timecode" => "$timecode",
						"timecode_type" => "$timecode_type",
						"data" =>"$data",
						"assetID" =>"$id"
						); 
			print_r($result_array);   */  
		}
	}
	else
	{
		header('HTTP/1.1 401 Authorization Required');
		//echo "Date: ".gmdate('F j, Y, g:i:s')." GMT<br />";
		//	echo "Location: https://api.mathinstitutes.org/metadata/v1/asset/2341<br />";
		echo "{\"error\": \"Permission required to update this institute asset.\"}";
	}
	
}
?>